package com.displayCongress;

import android.app.ActionBar;
import android.app.Activity;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.net.URI;

/**
 * @author wouter
 * Date: 12/11/12
 * Time: 11:56 AM
 */
public class SendActivity extends Activity {
	enum SendType
	{
		url,
		file,
		none
	}
	
	private SendType sendtype = SendType.none;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences settings = getSharedPreferences("serverSettings", 0);

        if(MainActivity.congressSocket == null || !MainActivity.congressSocket.isLoggedIn()) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }

        Thread thread = new Thread(new ConnectionThread(settings));
        thread.start();

        setContentView(R.layout.send);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);

        // Get intent, action and MIME type
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();

        if (Intent.ACTION_SEND.equals(action) && (type.equals("text/plain") || type.equals("text/html")))
        {
            handleUrl(intent);
        }
        else if (Intent.ACTION_SEND.equals(action))
        {
			handleFile(intent);
        }
    }

    protected void handleUrl(Intent intent) {
        ((EditText) findViewById(R.id.urlField)).setText(intent.getStringExtra(Intent.EXTRA_TEXT));
        sendtype = SendType.url;
    }

    protected void handleFile(Intent intent) {
        Uri uri = intent.getData();
    	if (uri == null)
    	{
    		uri = (Uri) intent.getExtras().get(Intent.EXTRA_STREAM);
    	}
    	
        File file = new File(uri.getPath());
        
        if (!file.exists())
        {
        	file = new File(getRealPathFromURI(uri));
        }
        
        if (file.exists())
        {
	        ((EditText) findViewById(R.id.urlField)).setText(file.getAbsolutePath());
	        sendtype = SendType.file;
        }
    }

    public void onSend(View view) {
        String text = ((EditText) findViewById(R.id.urlField)).getText().toString();

        makeToast("Sending " + text);

        if (sendtype.equals(SendType.url))
		{
        	sendURL(text);
        }
        else if (sendtype.equals(SendType.file))
        {
        	try
			{
				sendFile(text);
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
        }
    }

    public void makeToast(String message) {
        // with jam obviously
        // I like them with cheese too :)
        Toast.makeText(this.getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; go home
                Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                finish();
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    protected void sendURL(String url) {
        if(MainActivity.congressSocket.isConnected()) {
            System.out.println(MainActivity.congressSocket.sendURL(url));
        }
    }
    
    protected void sendFile(String path) throws IOException
    {
    	if(MainActivity.congressSocket.isConnected()) {
            System.out.println(MainActivity.congressSocket.send(new File(path)));
        }
    }
    
    private String getRealPathFromURI(Uri contentURI) 
    {
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null); 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        return cursor.getString(idx); 
    }
}